#!/usr/bin/env bash
source "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/config"
set -eo pipefail
[[ $DOKKU_TRACE ]] && set -x

plugin-install() {
  pull-docker-image() {
    declare IMAGE="$1"
    if [[ "$PLUGIN_DISABLE_PULL" == "true" ]]; then
      echo " !     ${PLUGIN_DISABLE_PULL_VARIABLE} environment variable detected. Not running pull command." 1>&2
      echo " !        docker pull ${IMAGE}" 1>&2
      return
    fi
    if [[ "$(docker images -q "${IMAGE}" 2>/dev/null)" == "" ]]; then
      docker pull "${IMAGE}"
    fi
  }

  pull-docker-image "${PLUGIN_IMAGE}:${PLUGIN_IMAGE_VERSION}"
  pull-docker-image "$PLUGIN_BUSYBOX_IMAGE"
  pull-docker-image "$PLUGIN_AMBASSADOR_IMAGE"
  pull-docker-image "$PLUGIN_S3BACKUP_IMAGE"
  pull-docker-image "$PLUGIN_WAIT_IMAGE"

  mkdir -p "$PLUGIN_DATA_ROOT" || echo "Failed to create $PLUGIN_SERVICE data directory"
  chown dokku:dokku "$PLUGIN_DATA_ROOT"

  mkdir -p "$PLUGIN_CONFIG_ROOT" || echo "Failed to create $PLUGIN_SERVICE config directory"
  chown dokku:dokku "$PLUGIN_CONFIG_ROOT"

  rm -f "/etc/sudoers.d/dokku-${PLUGIN_COMMAND_PREFIX}*"
  _SUDOERS_FILE="/etc/sudoers.d/dokku-${PLUGIN_COMMAND_PREFIX}"

  touch "$_SUDOERS_FILE"
  cat >"$_SUDOERS_FILE" <<EOL
%dokku ALL=(ALL) NOPASSWD:/bin/rm -f /etc/cron.d/dokku-${PLUGIN_COMMAND_PREFIX}-*
%dokku ALL=(ALL) NOPASSWD:/bin/chown root\:root /etc/cron.d/dokku-${PLUGIN_COMMAND_PREFIX}-*
%dokku ALL=(ALL) NOPASSWD:/bin/chmod 644 /etc/cron.d/dokku-${PLUGIN_COMMAND_PREFIX}-*
%dokku ALL=(ALL) NOPASSWD:/bin/mv ${PLUGIN_DATA_ROOT}/.TMP_CRON_FILE /etc/cron.d/dokku-${PLUGIN_COMMAND_PREFIX}-*
%dokku ALL=(ALL) NOPASSWD:/bin/chown 8983 $PLUGIN_DATA_ROOT/*
%dokku ALL=(ALL) NOPASSWD:/bin/chgrp 8983 $PLUGIN_DATA_ROOT/*
EOL

  chmod 0440 "$_SUDOERS_FILE"
}

plugin-install "$@"
